package com.suke.czx.modules.wx.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.suke.czx.common.utils.DateUtils;
import com.suke.czx.common.utils.JsonResult;
import com.suke.czx.common.utils.UUIDS;
import com.suke.czx.modules.wx.config.WxMpConfiguration;
import com.suke.czx.modules.wx.config.WxPayProperties;
import com.suke.czx.modules.wx.cons.Constant;
import com.suke.czx.modules.wxadmin.entity.DkExchangeCodeEntity;
import com.suke.czx.modules.wxadmin.entity.DkReadPlanEntity;
import com.suke.czx.modules.wxadmin.entity.DkResourceEntity;
import com.suke.czx.modules.wxadmin.entity.DkUserEntity;
import com.suke.czx.modules.wxadmin.service.DkExchangeCodeService;
import com.suke.czx.modules.wxadmin.service.DkReadPlanService;
import com.suke.czx.modules.wxadmin.service.DkResourceService;
import com.suke.czx.modules.wxadmin.service.DkUserService;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;

@RestController
@RequestMapping("/wx/code")
public class WxCodeController extends BaseController{
	
	@Autowired
	private DkExchangeCodeService dkExchangeCodeService;
	
	@Autowired
	private DkUserService dkUserService;
	@Autowired
	private DkResourceService dkResourceService;
	@Autowired
	private DkReadPlanService dkReadPlanService;
	@Autowired 
	private WxPayProperties wxPayProperties;
	@RequestMapping("/exchange")
	public String exchange(String code){
		WxMpUser wxMpUser = (WxMpUser) getSession().getAttribute(Constant.WX_USER);
		if (null == wxMpUser) {
			return new JsonResult(24, "用户未登录，请先登录！").toJson();
		}
		if(null==code||"".equals(code)){
			return new JsonResult(-1, "code不能为空！").toJson();
		}
		DkExchangeCodeEntity dece =  dkExchangeCodeService.queryObject(code);
		if(null==dece||dece.getOpenid()!=null){
			return new JsonResult(-1, "您输入的为无效兑换码！").toJson();
		}
		DkUserEntity dkUser = dkUserService.queryObject(wxMpUser.getOpenId(),false);
		if(dkUser.getState()==1){
			return new JsonResult(-1, "您已经是付费用户了，不需要再付费了！").toJson();
		}
		//处理付费逻辑，生成学习计划
		//1、锁定兑换码
		Date date = new Date();
		dece.setOpenid(wxMpUser.getOpenId());
		dece.setExchangeTime(date);
		dkExchangeCodeService.update(dece);
		
		//2、更新用户状态
		List<DkResourceEntity> dkrs = dkResourceService.querySysResourceByCourseId(1);
		dkUser.setOrdertime(date);
		dkUser.setState(1);
		dkUser.setStartTime(DateUtils.getDate(date, 0));
		dkUser.setEndTime(DateUtils.getDate(date, dkrs.size() - 1));
		dkUser.setCreatetime(new Date());
		dkUserService.update(dkUser);
		
		List<DkReadPlanEntity> plans = dkReadPlanService.queryUserReadPlanById(dkUser.getOpenid());
		if (null == plans || plans.size() == 0) {
			// 2、构建学习计划
			plans = new ArrayList<DkReadPlanEntity>();
			for (int i = 0; i < dkrs.size(); i++) {
				DkReadPlanEntity plan = new DkReadPlanEntity();
				plan.setId(UUIDS.getUUID());
				plan.setCreatetime(new Date());
				plan.setReadDate(DateUtils.getDate(date, i));
				plan.setResourceId(dkrs.get(i).getId());
				Calendar cal = Calendar.getInstance();
				int h = cal.get(Calendar.HOUR_OF_DAY);
				plan.setStatus(0);
				if (h == 22 || h == 23) {
					if (i == 0) {
						plan.setStatus(1);
					}
				}
				plan.setUserId(dkUser.getOpenid());
				plan.setSendState(0);
				plans.add(plan);
			}
			dkReadPlanService.batchInsertUserReadPlan(plans);
		}
		new Thread(new Runnable() {
			public void run() {
				//"wx110e4b18284caf04"
				WxMpService wxMpService = WxMpConfiguration.getMpServices().get(wxPayProperties.getAppId());//

				// 演示10s秒钟发送模板消息
				try {
					
					WxMpUser wxMpUser = wxMpService.getUserService().userInfo(dkUser.getOpenid());
					if (!wxMpUser.getSubscribe()) {
						return;
					}
					// 发送模板消息 --- 给订购成功的人
					WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder().toUser(wxMpUser.getOpenId())
							.templateId(wxPayProperties.getTidBuySuccess()).build();
					templateMessage.addData(new WxMpTemplateData("first", "您已成功订购以下课程\r\n\r\n", "#000000"));
					templateMessage.addData(new WxMpTemplateData("keyword1", "《精读诗词·210天学习计划》", "#000000"));
					templateMessage.addData(new WxMpTemplateData("keyword2", dkUser.getStartTime(), "#000000"));
					templateMessage.addData(new WxMpTemplateData("keyword3", "长期有效，可以反复听", "#000000"));
					templateMessage.addData(
							new WxMpTemplateData("remark", "点击下方『今日阅读』即刻开启今天的课程，记得学习哟~\r\n\r\n↓↓↓", "#000000"));
					
					wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
		return new JsonResult(200, "兑换成功！").toJson();
		
	}
	

}
